import 'dart:async';

import 'package:fijkplayer/fijkplayer.dart';
import 'package:get/get.dart';
import 'package:shared_preferences/shared_preferences.dart';

import 'widget/custom_fijkplayer.dart';
import 'widget/player_show_config.dart';

class VideoPlayerLogic extends GetxController {
  final FijkPlayer player = FijkPlayer();
  ShowConfigAbs v_cfg = PlayerShowConfig();
  Timer? timer;
  Timer? seekTimer;
  // 当前播放的视频chapterId
  final curActiveIdx = 0.obs;

  @override
  void onClose() {
    timer!.cancel();
    seekTimer!.cancel();
    player.release();
    super.onClose();
  }

  @override
  void onInit() {
    super.onInit();
  }

  /// 更新当前播放的集ID
  setActiveChapterId(int activeId) {
    curActiveIdx.value = activeId;
  }

  /// 开启自动保存播放进度
  /// 5秒保存一次
  startSavePlayerCurrentPosition(
      {videoId, String? sourceId, int? activeChapterId}) async {
    SharedPreferences prefs = await SharedPreferences.getInstance();
    timer = Timer.periodic(new Duration(seconds: 5), (timer) {
      // 0:23:40.221000
      int sec = player.currentPos.inMilliseconds;
      if (player.isPlayable() && sec > 0) {
        prefs.setInt('$sourceId:$videoId:$activeChapterId:position', sec);
        print('autoSavePlayerCurrentPosition: $sec');
      }
    });
  }

  /// 停止保存播放进度
  stopSavePlayerCurrentPosition() {
    if (timer != null) {
      timer!.cancel();
    }
  }

  /// 定位到保存的播放进度
  seekToCachedPosition(
      {videoId, String? sourceId, int? activeChapterId}) async {
    SharedPreferences prefs = await SharedPreferences.getInstance();
    activeChapterId = activeChapterId ?? curActiveIdx.value;
    // 监听当前position
    seekTimer = Timer.periodic(Duration(seconds: 1), (timer) {
      if (player.isPlayable()) {
        print('播放状态: true & position = ${player.currentPos.inMilliseconds}');
        // 当position > 1，seekTo
        var key = '$sourceId:$videoId:$activeChapterId:position';
        int sec = prefs.getInt(key) ?? 0;
        print('seekToCachedPosition $key = $sec');
        if (sec != 0) {
          player.seekTo(sec);
        }
        // 重置播放进度保存调度
        startSavePlayerCurrentPosition(
            videoId: videoId,
            sourceId: sourceId,
            activeChapterId: activeChapterId);
        // 关闭当前调度
        timer.cancel();
      }
    });
  }
}
